﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace ES.Shared.Data
{
    [Serializable]
    public class KeyColumnInfoCollection : Collection<KeyColumnInfo>
    {
        public void AddRange(IEnumerable<KeyColumnInfo> items)
        {
            foreach (KeyColumnInfo item in items)
            {
                Add(item);
            }
        }

        public KeyColumnInfo this[string columnName]
        {
            get
            {
                KeyColumnInfo found = FindKeyColumnByColumnName(columnName).FirstOrDefault();

                if (found == null)
                    throw new KeyNotFoundException();

                return found;
            }
        }

        private IEnumerable<KeyColumnInfo> FindKeyColumnByColumnName(string columnName)
        {
            return from column in this
                   where column.ColumnName.Equals(columnName, StringComparison.InvariantCultureIgnoreCase)
                   select column;
        }

        protected override void InsertItem(int index, KeyColumnInfo item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            if (FindKeyColumnByColumnName(item.ColumnName).Count() == 0)
                base.InsertItem(index, item);
            else
                throw new ArgumentException(string.Format(LanguageResource.Error_DoubleColumnName, item.ColumnName));
        }

        protected override void SetItem(int index, KeyColumnInfo item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            if (FindKeyColumnByColumnName(item.ColumnName).Count() == 0)
                base.SetItem(index, item);
            else
                throw new ArgumentException(string.Format(LanguageResource.Error_DoubleColumnName, item.ColumnName));
        }
    }
}
